package services

import (
	"examination/rpc/global"
	"examination/rpc/models/dao"
	"gorm.io/gorm"
)

func CreateUser(user dao.User) error {
	return global.Db.Create(&user).Error
}

func CreateTestQuestions(questions dao.TestQuestions) error {
	return global.Db.Create(&questions).Error
}

func QueryTestQuestionsByTopic(topic string) (list []*dao.TestQuestions, err error) {
	err = global.Db.Where("topic = ?", topic).First(&list).Error
	return list, err
}

func UpdateAnswer(topic, Answer string) error {
	var TestQuestions dao.TestQuestions
	return global.Db.Model(&TestQuestions).Where("topic = ?", topic).Update("answer", Answer).Error
}

func DeleteTestQuestionsByTopic(topic string) error {
	var TestQuestions dao.TestQuestions
	return global.Db.Where("topic = ?", topic).Delete(&TestQuestions).Error
}

func CreateTestPaper(paper dao.TestPaper) error {
	return global.Db.Create(&paper).Error
}

func QueryTestPaperByComposingType(testPaperName string) (list []*dao.TestPaper, err error) {
	err = global.Db.Where("test_paper_name = ?", testPaperName).First(&list).Error
	return list, err
}

func TestPaperListByComposingType(composingType, page, pageSize int) (list []*dao.TestPaper, err error) {
	err = global.Db.Where("composing_type = ?", composingType).Scopes(Paginate(page, pageSize)).Find(&list).Error
	return list, err
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func CreateExamDetails(details dao.ExamDetails) error {
	return global.Db.Create(&details).Error
}

func QueryExamDetailsByName(name string) (list []*dao.ExamDetails, err error) {
	err = global.Db.Where("name = ?", name).First(&list).Error
	return list, err
}

func GetUserInfo(name string) (user dao.User, err error) {
	err = global.Db.Where("name = ?", name).First(&user).Error
	return user, err
}

func CreateExamStatus(status dao.ExamStatus) error {
	return global.Db.Create(&status).Error
}
